package stu.elasticsearch.jdbc;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 一句简洁的说明
 *
 * @author lzy
 * @date 2021/10/6 18:29
 */
public class EsTool {
    public static final String URL_PREFIX = "jdbc:es://";

    public static boolean canAccept(String url) {
        return !isEmpty(url) && url.trim().startsWith(URL_PREFIX);
    }

    public static boolean isEmpty(CharSequence str) {
        return str == null || str.length() == 0;
    }

    public static boolean isBlank(CharSequence str) {
        int length;

        if ((str == null) || ((length = str.length()) == 0)) {
            return true;
        }

        for (int i = 0; i < length; i++) {
            // 只要有一个非空字符即为非空字符串
            if (false == isBlankChar(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public static boolean isBlankChar(int c) {
        return Character.isWhitespace(c)
                || Character.isSpaceChar(c)
                || c == '\ufeff'
                || c == '\u202a'
                || c == '\u0000';
    }

    public static int parseInt(String strNum, int defVal) throws NumberFormatException {
        if (isBlank(strNum)) {
            return 0;
        }
        if (strNum.toLowerCase().startsWith("0x")) {
            // 0x04表示16进制数
            return Integer.parseInt(strNum.substring(2), 16);
        }
        try {
            return Integer.parseInt(strNum);
        } catch (NumberFormatException e) {
            return defVal;
        }
    }

    public static byte[] bytes(CharSequence str, Charset charset) {
        if (str == null) {
            return null;
        }

        if (null == charset) {
            return str.toString().getBytes();
        }
        return str.toString().getBytes(charset);
    }

}
